rm(list=ls())
library(tidyverse)
library(readxl)

# Read data
file <- list.files(here::here("data","raw","IBGE"), pattern = "tab6784", full.names = T)
gdp_deflator <- read_excel(file,
                           sheet = "PIB - deflator - variação an...",
                           skip = 3,
                           col_names = c("region","year","gdp_deflator"),
                           col_types = c("text","numeric","numeric"),
                           na = "...") %>% 
  filter(!is.na(gdp_deflator)) %>% 
  select(year,gdp_deflator)

# Create price index normalized to 1 = 1996
gdp_deflator <- gdp_deflator %>% 
  mutate(gdp_deflator_index = cumprod(ifelse(year == 1996,1,1+gdp_deflator/100)))

# Rebase to 2016 = 1

gdp_deflator_2016 <- gdp_deflator %>% 
  filter(year == 2016) %>% 
  rename(index_base = gdp_deflator_index) %>% 
  pull(index_base)

gdp_deflator <- gdp_deflator %>% 
  mutate(gdp_deflator_index = gdp_deflator_index/gdp_deflator_2016) %>% 
  select(year,gdp_deflator = gdp_deflator_index)


#SaveRdS ----

write_rds(gdp_deflator,here::here("data","processed","gdp_deflator.rds"))


